package com.kamfu.makingjavafunctional.example01;

import com.kamfu.function.common.Effect;
import com.kamfu.function.common.Function;
import com.kamfu.makingjavafunctional.Result02;

import java.util.regex.Pattern;

/**
 * validate 方法不应该依赖于 sendVerificationMail logError
 * 1.创建一个表示作用的接口Effect，对sendVerificationMail  logError的抽象
 * 2.创建Result02：可以处理Effect的结果包装类
 * 3.修改函数变量emailChecker
 * 4.删除validate方法
 */
public class EmailValidation05 {

    static Pattern emailPattern =
            Pattern.compile("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$");


    static Function<String, Result02<String>> emailChecker = s -> {
        if (s == null) {
            return Result02.failure("email must not be null");
        } else if (s.length() == 0) {
            return Result02.failure("email must not be empty");
        } else if (emailPattern.matcher(s).matches()) {
            return Result02.success(s);
        } else {
            return Result02.failure("email " + s + " is invalid.");
        }
    };

    static Effect<String> success= s->System.out.println("Verification mail sent to " + s);

    static Effect<String> error=s->System.err.println("Error message logged: " + s);;





    public static void main(String... args) {
        emailChecker.apply("this.is@my.email").bind(success,error);
        emailChecker.apply(null).bind(success,error);
        emailChecker.apply("").bind(success,error);
        emailChecker.apply("john.doe@acme.com").bind(success,error);
    }
}
